package program.Command;

import java.util.LinkedList;
import java.util.Random;

import program.SExpression;

import Exceptions.ElementPlacementError;
import Exceptions.IllegalCoordinateException;
import Exceptions.PickupError;
import Exceptions.TerminationError;
import roborally.Element;
import roborally.Robot;
import roborally.Item;
/**
 * A class representing a PICKUP-AND-USE command.
 * @author Jef Keijers/Bachelor of Science: Informatics
 * @version 1.0
 */

public class PickupAndUse extends Command {

	/**
	 * This method executes pickup-and-use and afterwards return null.
	 */
	@Override
	public Command execute(Robot robot) throws PickupError, TerminationError, IllegalCoordinateException, ElementPlacementError  {
		LinkedList <Element> elements=robot.getBoard().getPositionMap().get(robot.getPosition());
		
		if (elements.size()==1) {
			return null; // Als enkel de robot erop staat kan hij niks oppakken, anders komt hij in infinite loop
		}
		
		Random random=new Random();
		int randomnumber=random.nextInt(elements.size());
		while (elements.get(randomnumber) instanceof Robot) {
			randomnumber=((randomnumber+1)%elements.size());
		}
		
		Item item=(Item)elements.get(randomnumber);
		robot.pickUp(item); 
		robot.use(item);
		return null;
	}
	
	/**
	 * This method returns the SExpression representation of pickups-and-use.
	 */
	@Override
	public SExpression toSExpression() {
		return this.makeSingletonSExpressionList("pickup-and-use");
	}

	

}
